package com.example.api.controller;

import com.example.api.exception.CustomException;
import com.example.api.util.KaptchaUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;

import static com.example.api.dto.ResStatusCode.KAPTCHA_IMAGE_ERROR;


@RestController
@RequestMapping("/api/kaptcha")
@Api("验证码生成和验证码接口")
public class KaptchaController {

    private static final Logger log = LoggerFactory.getLogger(KaptchaController.class);

    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("/image")
    public void getKaptcha(HttpServletRequest request,
                           HttpServletResponse response,
                           @RequestParam(required = true)
                           String phone
                            ) throws IOException {


        //千万要给我记住这里   不然你的cache里面 怎么找都找不到缓存 憨憨~
        response.setDateHeader("Express",0);
        response.setHeader("Cache-Control","no-store,no-cache,post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");

        //设置返回类型为图片
        response.setContentType("image/jpeg");

        //获取随机验证码
        String capText = defaultKaptcha.createText();
        //放到缓存中
        String key = KaptchaUtil.IMG_KAPTCHA_KEY+phone;
        redisTemplate.boundValueOps(key).set(capText, Duration.ofMinutes(10));

        //生成图片
        BufferedImage bi = defaultKaptcha.createImage(capText);

        ServletOutputStream outputStream = response.getOutputStream();

        ImageIO.write(bi, "jpg",outputStream);

        try {
            outputStream.flush();
        }finally {
            outputStream.close();
        }

    }

    /**
     * 前端验证
     * @param code
     * @param phone
     * @return
     */
    @GetMapping("/checkKaptcha")
    public ResponseEntity<String> checkKaptcha(String code,String phone) {

        //从缓存中获取图片验证码
        String key = KaptchaUtil.IMG_KAPTCHA_KEY+phone;
        String cacheCode = redisTemplate.boundValueOps(key).get();
        if (StringUtils.hasText(cacheCode) && cacheCode.equalsIgnoreCase(code)) {
            return ResponseEntity.ok("验证成功");
        }else{
            //return ResponseEntity.badRequest().build();
            throw new CustomException(phone,KAPTCHA_IMAGE_ERROR.getCode(),KAPTCHA_IMAGE_ERROR.getMessage());
        }
    }


    @GetMapping("/sms")
    public ResponseEntity<String> getSmsCode(String phone) {

        String capText = defaultKaptcha.createText();

        //放到缓存
        String key = KaptchaUtil.SMS_KAPTCHA_KEY+phone;

        redisTemplate.boundValueOps(key).set(capText,Duration.ofMinutes(10));

        //通过短信网关发送给客户
        log.info("{} 已发送短信 {}",phone,capText);
        return ResponseEntity.ok("已发送");
    }


}
